<template>
	<view class="container">
		<view v-if='currentStep < 3' class="header">
			<u-steps :current="currentStep" active-color="#19be6b">
				<u-steps-item title="选择数量"></u-steps-item>
				<u-steps-item title="选择区域"></u-steps-item>
				<u-steps-item title="支付费用"></u-steps-item>
				<u-steps-item title="完成认购"></u-steps-item>
			</u-steps>
		</view>

		<view class="content">
			<!-- 步骤1: 选择数量 -->
			<view v-if="currentStep === 0" class="step-content">
				<view class="step-title">选择数量</view>
				<!--        <view class="step-subtitle">请选择你要认养的数量，一共有8000棵树可以认养哟</view> -->
				<view class="card">
					<view class="number-selector">
						<view style='margin: auto;'>
							<img :src='cover' style='width:150px;height:150px' />
						</view>
						<!-- <view class="remaining-trees">剩余可认养: {{ remainingTrees }}棵</view> -->
						<view class="stepper-container">
							<text>认购数量:</text>
							<u-number-box v-model="selectedCount" :min="1" integer buttonSize='50'
								inputWidth='60px'></u-number-box>
							<text>{{unit}}</text>
						</view>
						<view class="price-display">总计: ￥{{ totalPrice.toFixed(2) }}</view>
					</view>
				</view>
				<view v-if='product.description' class='description'>
					<u-parse :content="product.description"></u-parse>
				</view>
				<view class='footer'>
					<view style='padding:10px'>
						<u-button type='primary' text='下一步' @click='nextStep'></u-button>
					</view>
				</view>
			</view>

			<!-- 步骤2: 选择地块 -->
			<view v-if="currentStep === 1" class="step-content">
				<view class="step-title">选择区域
				<text v-if='region && region.name'>当前区域</text>
				<text v-if='region && region.name' style='color:#19be6b'>【{{region.name}}】</text>
				</view>
				<view class="card">
					<view class="map-container">
						<view>
							<view v-if='region && region.parent' style='float:right;padding-right:10px;margin-bottom: -50px;'>
								<text @click="goBackRegion(region)" style='color:#909399;font-size: 18px;'>返回</text>
							</view>
							
							<image :src='region.picture' :style='mapStyle'
								mode="aspectFit" @click="handleImageClick" />
						</view>
						<view v-if='coupons && coupons.length > 0' class="plot-selection">
							<view class="plot-title">可选区域</view>
							<u-radio-group v-model="couponRegion.id" placement="column" :labelDisabled='true'>
								<u-radio v-for="(item, index) in coupons" :key="index" :name="item.region.id"
									:disabled="item.remains < selectedCount">
									<view @click='chooseCoupon(item)'
										style='margin:5px 0px;font-size:18px;colot:#606266;'>
										{{ item.region.__toString }} (剩余: {{ item.remains }}{{unit}})
									</view>
								</u-radio>
							</u-radio-group>
						</view>
						<view v-else style='margin-top:20px;padding:10px;color:#909399;text-align: center;'>
							<view>请点击地图对应区域</view>
						</view>
					</view>
				</view>
				<view class='footer'>
					<view style='padding:10px'>
						<u-row>
							<u-col span='6'>
								<view style='margin:0px 5px;'>
									<u-button type='warning' text='上一步' @click='prevStep'></u-button>
								</view>
							</u-col>
							<u-col span='6'>
								<view style='margin:0px 5px;'>
									<u-button type='primary' text='下一步' @click='checkRegion'></u-button>
								</view>
							</u-col>
						</u-row>
					</view>
				</view>
			</view>

			<!-- 步骤3: 支付费用 -->
			<view v-if="currentStep === 2" class="step-content">
				<view class="step-title">支付费用</view>
				<view class="step-subtitle">请选择支付方式完成认购</view>

				<view class="card">
					<view class="order-summary">
						<view class="summary-item">
							<text>认购数量:</text>
							<text>{{ selectedCount }}{{unit}}</text>
						</view>
						<view class="summary-item">
							<text>所属区域:</text>
							<text>{{ couponRegion.name }}</text>
						</view>
						<view class="summary-item total">
							<text>总计:</text>
							<text>￥{{ totalPrice.toFixed(2) }}</text>
						</view>
					</view>
				</view>
				<view v-if='coupon && coupon.description' class='card'>
					<u-parse :content="coupon.description"></u-parse>
				</view>
				<view class='footer'>
					<view style='padding:10px'>
						<u-row>
							<u-col span='6'>
								<view style='margin:0px 5px;'>
									<u-button type='warning' text='上一步' @click='prevStep'></u-button>
								</view>
							</u-col>
							<u-col span='6'>
								<view style='margin:0px 5px;'>
									<u-button v-if='phone == ""' type='success' text='支付' open-type="getPhoneNumber"
										@getphonenumber="getPhoneNumber"></u-button>
									<u-button v-else type='success' text='支付' @click='creteOrder'></u-button>
								</view>
							</u-col>
						</u-row>
					</view>
				</view>
			</view>

			<!-- 步骤4: 完成认养 -->
			<view v-if="currentStep === 3" class="step-content">
				<view v-if='couponRegion.picture'>
					<img :src='couponRegion.picture' style='width:100%;height:auto' mode='widthFix' />
				</view>
				<view v-else class="success-container">
					<u-icon name="checkmark-circle-fill" color="#19be6b" size="80"></u-icon>
					<view class="success-title">认购成功!</view>
					<view class="success-subtitle">恭喜您已经成功认购</view>

					<image :src="cover" mode="aspectFit" class="success-image"></image>

					<view class="success-details">
						<view class="detail-item">
							<text>认购编号:</text>
							<text>{{orderNo}}</text>
						</view>
						<view class="detail-item">
							<text>认购数量:</text>
							<text>{{ selectedCount }}{{unit}}</text>
						</view>
						<view class="detail-item">
							<text>认购区域:</text>
							<text>{{ couponRegion.name }}</text>
						</view>
						<view v-if='coupons' class="detail-item">
							<text>有效期限:</text>
							<text>{{$u.timeFormat(coupons[0].useEndTime, 'yyyy年mm月dd日')}}</text>
						</view>
					</view>
				</view>
				<view class='footer'>
					<view style='padding:10px'>
						<u-button type='primary' text='查看' @click='toTree' shape='circle'></u-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import wechatPay from '@/utils/wechat-pay.js'
	export default {
		data() {
			return {
				currentStep: 0,
				selectedCount: 1,
				treePrice: 0,
				cover: '/static/tree.png',
				spec: 0,
				unit: '份',
				regions: [],
				chooseRegion: '',
				coupons: [],
				couponRegion: {
					id: 0,
					name: ''
				},
				orderNo: '',
				product: '',
				region: '',
				paths: [],
				id: 0,
				coupon: '',
				mapStyle: 'display: block;width:360px;height:360px;margin:auto',
				mapWidth: 360,
				phone: ''
			}
		},
		computed: {
			totalPrice() {
				return this.selectedCount * this.treePrice;
			}
		},
		onShow() {

		}, 
		onLoad(options) {
			if (typeof(options.id) != 'undefined') {
				this.request.get(`api/options/IS_REVIEW`).then((res) => {
					if(res.data.value == true){
						uni.showModal({
							title: '',
							content: '您找的东西已经丢失，请确定是否从正确入口进入！',
							showCancel: false,
							success: () => {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}
						})
						return
					}else{
						this.id = options.id
						let token = uni.getStorageSync('api_token')
						const systemInfo = uni.getSystemInfoSync();
						this.mapWidth = systemInfo.screenWidth - 20;
						console.log('屏幕宽度',this.mapWidth)
						if(this.mapWidth > 0){
							this.mapStyle = `display: block;width:${this.mapWidth}px;height:${this.mapWidth}px;margin:auto`
						}
						uni.showLoading()
						if(token == ''){
							let _this = this
							uni.login({
								success(result) {
									let data = {
										code: result.code,
									}
									if(typeof(options.recommendedUser) != 'undefined'){
										data.recommendedUser = options.recommendedUser
									}else{
										data.recommendedUser = 2
									}
									_this.request.get(`wechat/mini/login`, data).then((res) => {
										uni.setStorageSync('api_token', res.data.token)
										_this.request.get(`api/user`,{
											'@expands': "['entity.profile']"
										}).then((res) => {
											_this.phone = res.data.profile.__metadata.phone
											uni.setStorageSync('userId',res.data.id)
											_this.getProduct()
										})
									})
								}
							})
						}else{
							this.request.get(`api/user`,{
								'@expands': "['entity.profile']"
							}).then((res) => {
								if(res.data.profile.__metadata.phone){
									this.phone = res.data.profile.__metadata.phone
								}
								this.getProduct()
							})
						}
					}
				})
			}
		},
		methods: {
			getProduct(){
				this.request.get(`api/products/${this.id}`, {
					'@expands': "['entity.specifications','entity.category']",
				}).then((res) => {
					uni.setNavigationBarTitle({
						title: res.data.name
					})
					if (res.data.isOnSlae == false) {
						uni.showModal({
							title: '',
							content: '项目已结束！',
							showCancel: false,
							success: () => {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}
						})
						return
					}
					console.log('product', res.data)
					this.product = res.data
					this.cover = res.data.cover ? res.data.cover : '/static/tree.png'
					this.treePrice = parseFloat(res.data.specifications[0].__metadata.price)
					this.spec = res.data.specifications[0]
					this.unit = res.data.specifications[0].__metadata.name
					let typeId = res.data.category.__metadata.type.id
					// 查product.category.type对应的顶级region
					this.request.get(`api/regions`, {
						'@filter': `entity.getType().getId() == ${typeId} && !entity.getParent()`
					}).then((res) => {
						console.log('topRegion', res.data)
						if (res.data && res.data.length > 0) {
							this.getRegionChildren(res.data[0].id)
							uni.hideLoading()
						}
					})
				})
			},
			goBackRegion(region){
				if(region.parent && region.parent.id){
					this.getRegionChildren(region.parent.id)
				}else{
					uni.showToast({
						title: '已经到最顶层！',
						icon: 'none'
					})
				}
			},
			handleImageClick(e) {
				if(this.paths.length > 0){
					uni.createSelectorQuery()
						.select('image')
						.boundingClientRect(res => {
					
							// 计算相对坐标
							const clickX = e.detail.x - 15
							const clickY = e.detail.y - 175
					
							// 转换为0-1范围的比例坐标
							let px = clickX * 800 / this.mapWidth
							let py = clickY * 800 / this.mapWidth
							let point = [px, py]
							console.log('坐标',point)
							let index = this.isPointInPaths(this.paths,point)
							console.log(index)
							if(index === -1){
								uni.showToast({
									title: '请点击范围',
									icon: 'none'
								})
							}else{
								this.region = this.regions[index]
								this.getRegionChildren(this.region.id)
							}
						})
						.exec()
				}
			},
			isPointInPaths(paths, point) {
				const [px, py] = point;

				for (let i = 0; i < paths.length; i++) {
					const path = paths[i];
					let crossCount = 0;
					const n = path.length;

					for (let j = 0; j < n; j++) {
						const [x1, y1] = path[j];
						const [x2, y2] = path[(j + 1) % n];

						// 射线交叉检测
						if ((y1 > py) !== (y2 > py)) {
							const intersectX = (py - y1) * (x2 - x1) / (y2 - y1) + x1;
							if (px <= intersectX) {
								crossCount++;
							}
						}
					}

					if (crossCount % 2 === 1) {
						return i; // 返回匹配的路径索引
					}
				}

				return -1; // 不在任何路径内
			},
			// 获取下级的region，如果这些下级region没有下级了，就获取对应的coupons
			getRegionChildren(id) {
				if (id > 0) {
					this.request.get(`api/regions`, {
						'@filter': `entity.getParent().getId() == ${id}`,
						'@expands': "['entity.parent']"
					}).then((res) => {
						console.log('regions', res.data)
						this.coupons = []
						// 只有一个无children，就直接过去对应coupons，有的，就加到regions数组，再执行下一次
						if (res.data[0].children.length > 0) {
							let paths = []
							for (let i of res.data) {
								if (i.paths) {
									let path = []
									for (let p of i.paths) {
										path.push([p.x, p.y])
									}
									paths.push(path)
								}
							}
							console.log('paths', paths)
							this.paths = paths
							this.regions = res.data
							this.region = res.data[0].parent.__metadata
						} else {
							this.paths = []
							
							this.getCouponsByRegion(res.data[0].parent.id)
						}
					})
				}
			},
			checkRegion() {
				if (this.couponRegion.id == 0) {
					uni.showToast({
						title: '请先选择区域',
						icon: 'none'
					})
				} else {
					this.nextStep()
				}
			},
			chooseCoupon(coupon) {
				console.log(coupon, this.selectedCount)
				if (coupon.remains >= this.selectedCount) {
					this.couponRegion = coupon.region.__metadata
					this.coupon = coupon
				}
			},
			getCouponsByRegion(id) {
				uni.showLoading()
				this.chooseRegion = id
				this.couponRegion = {
					id: 0,
					name: ''
				}
				console.log(id)
				this.request.get(`api/coupons`, {
					'@filter': `entity.getRegion().getParent().getId() == ${id}`,
					'@expands': "['entity.region']",
					'@groupBy': `entity.region`
				}).then((res) => {
					console.log('coupons', res.data)
					this.coupons = res.data
					if (res.data && res.data.length > 0) {
						for (let i of res.data) {
							if (i.remains >= this.selectedCount) {
								this.couponRegion = i.region.__metadata
								this.coupon = i
								break
							}
						}
					}
					uni.hideLoading()
				})
			},
			// 选择区域
			changeRegion(index, parentId) {
				console.log(index, parentId)
				let regions = []
				for (let i = 0; i <= index; i++) {
					console.log(i)
					regions.push(this.regions[i])
				}
				this.regions = regions
				console.log(regions)
				this.getRegionChildren(parentId)
			},
			nextStep() {
				if (this.currentStep == 0) {
					for (let i of this.coupons) {
						if (i.remains >= this.selectedCount) {
							this.couponRegion = i.region.__metadata
							break
						}
					}
					this.currentStep++
				} else if (this.currentStep < 3) {
					this.currentStep++;
				} else {
					uni.showToast({
						title: '认购完成',
						icon: 'success'
					});
				}
			},
			prevStep() {
				if (this.currentStep > 0) {
					this.currentStep--;
				}
			},
			toTree() {
				if (this.product.category.__metadata.type.id == 2) {
					uni.switchTab({
						url: '/pages/cart/index'
					})
				} else {
					uni.redirectTo({
						url: '/pages/mine/coupon'
					})
				}
			},
			getPhoneNumber(e) {
				let _this = this
				if (typeof(e.detail.iv) == 'undefined') {
					uni.showToast({
						title: '获取失败,请重试',
						icon: 'none'
					})
					return
				} else {
					uni.showLoading()
					uni.login({
						provider: "weixin",
						success: function(res) {
							let data = {
								code: res.code
							}
							_this.request.get("wechat/mini/login", data).then((res) => {
								if (res.data.data.session_key) {
									let data = {
										sessionKey: res.data.data.session_key,
										iv: e.detail.iv,
										encryptedData: e.detail.encryptedData,
									}
									_this.request.post(`wechat/decrypt-data`, data).then((res) => {
										_this.phone = res.data.phoneNumber
										//更新手机号码
										_this.request.put(`api/user-profile`, {
											phone: res.data.phoneNumber
										}).then((res) => {
											console.log(res)
											_this.creteOrder()
										})
										uni.hideLoading()
									})
								} else {
									uni.hideLoading()
									uni.showToast({
										title: '获取手机号码失败！',
										icon: 'none'
									})
								}
							})
						},
					});
				}
			},
			creteOrder() {
				if (this.couponRegion.id) {
					uni.showLoading()
					this.request.get(`api/coupons`, {
						'@filter': `entity.getRegion().getId() == ${this.couponRegion.id}`
					}).then((res) => {
						if (res.data && res.data.length > 0) {
							if (res.data[0].remains >= this.selectedCount) {
								let orderData = {
									store: 1,
									items: [{
										specification: this.spec.id,
										quantity: this.selectedCount
									}],
									region: this.couponRegion.id
								}
								this.request.post(`api/orders`, orderData).then((res) => {
									uni.hideLoading()
									this.orderNo = res.data.no
									let invoice = res.data.invoice
									if (invoice.id) {
										uni.hideLoading()
										wechatPay(invoice.id).then((res) => {
											uni.hideLoading()
											this.currentStep = 3
											uni.showModal({
												title: '',
												content: '购买成功！',
												showCancel: false,
												success: () => {}
											})
										}).catch((err) => {
											uni.hideLoading()
											uni.showModal({
												title: '',
												content: '支付失败，请重试',
												showCancel: false,
												success: () => {

												}
											})
										})
									}
								})
							} else {
								uni.hideLoading()
								uni.showModal({
									title: '',
									content: '该区域剩余量不足，请重新选择区域',
									showCancel: false,
									success: () => {
										this.currentStep = 1
									}
								})
							}
						} else {
							uni.hideLoading()
							uni.showModal({
								title: '',
								content: '该区域没有数量！',
								showCancel: false,
								success: () => {}
							})
						}
					})


				} else {
					uni.showToast({
						title: '请选择区域',
						icon: 'none'
					})
				}

			}
		}
	}
</script>

<style scoped>
	.footer {
		position: fixed;
		bottom: 0px;
		width: calc(100% - 40rpx);
		z-index: 3;
		background-color: #fff;
	}

	.container {
		display: flex;
		flex-direction: column;
		max-height: 100vh;
		overflow: auto;
		background-color: #f5f5f5;
		padding: 10px;
	}

	.header {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		height: 80px;
	}

	.content {
		flex: 1;
	}

	.step-content {
		margin-bottom: 20rpx;
	}

	.step-title {
		font-size: 36rpx;
		font-weight: bold;
		padding-bottom: 10rpx;
		color: #333;
		height: 25px;
	}

	.step-subtitle {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 30rpx;
	}

	.card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx 0px 60rpx 0px;
		margin-bottom: 20rpx;
	}

	.number-selector {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.remaining-trees {
		font-size: 28rpx;
		color: #19be6b;
		margin-bottom: 30rpx;
	}

	.stepper-container {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.stepper-container text {
		margin: 0 20rpx;
		font-size: 32rpx;
	}

	.price-display {
		font-size: 36rpx;
		font-weight: bold;
		color: #fa3534;
	}

	.map-container {
		width: 100%;
		margin: auto;
	}

	.plot-selection {
		margin-top: 30rpx;
	}

	.plot-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.order-summary {
		margin-bottom: 40rpx;
	}

	.summary-item {
		display: flex;
		justify-content: space-between;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.summary-item.total {
		font-weight: bold;
		font-size: 32rpx;
		color: #fa3534;
		border-bottom: none;
		margin-top: 10rpx;
	}

	.payment-methods {
		margin-top: 30rpx;
	}

	.payment-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.payment-option {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.payment-option text {
		margin-left: 15rpx;
	}

	.success-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
		padding: 40rpx;
		background-color: #fff;
		border-radius: 16rpx;
	}

	.success-title {
		font-size: 40rpx;
		font-weight: bold;
		color: #19be6b;
		margin: 20rpx 0 10rpx;
	}

	.success-subtitle {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 40rpx;
	}

	.success-image {
		width: 300rpx;
		height: 300rpx;
		margin: 30rpx 0;
		background-color: #f1f1f1;
		border-radius: 16rpx;
	}

	.success-details {
		width: 100%;
		margin-top: 30rpx;
	}

	.detail-item {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
		font-size: 28rpx;
	}

	.tree-footer {
		display: flex;
		justify-content: space-between;
		padding: 30rpx 0;
		background-color: #fff;
		border-top: 1rpx solid #eee;
	}

	.action-btn {
		width: 48%;
	}

	.description {
		background-color: #fff;
		margin-top: 20px;
		padding: 10px;
		border-radius: 10px;
		height:30vh;
		overflow: auto;
		padding-bottom:50px;
	}
</style>